package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * 将二叉搜索树变平衡
 */

public class Code1382 {
    public static void main(String[] args) {

    }

    public TreeNode balanceBST(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inorder(root, list);
        if (list.isEmpty()) return null;

        return buildBST(list, 0, list.size() - 1);
    }

    private void inorder(TreeNode root, List<Integer> list) {
        if (root == null) return;
        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }

    // 递归构建BST
    private TreeNode buildBST(List<Integer> nums, int left, int right) {
        if (left > right) return null;
        int mid = (left + right) >> 1;
        TreeNode root = new TreeNode(nums.get(mid));
        root.left = buildBST(nums, left, mid - 1);
        root.right = buildBST(nums, mid + 1, right);
        return root;
    }
}
